package com.jiuwu.spring.eshop.controller;

import com.jiuwu.spring.eshop.db.entity.BBS;
import com.jiuwu.spring.eshop.db.entity.Member;
import com.jiuwu.spring.eshop.db.entity.SubType;
import com.jiuwu.spring.eshop.respository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
public class IndexController {


    @Autowired
    VTypeRepository vTypeRepository;


    @Autowired
    VGoodsRepository vGoodsRepository;

    @Autowired
    PictureRepository pictureRepository;

    @Autowired
    BBSRepository bbsRepository;

    @Autowired
    GoodsRepository goodsRepository;


    @Autowired
    SubTypeRepository subTypeRepository;


    @Autowired
    CommentRepository commentRepository;

    @Autowired
    MemberRepository memberRepository;



    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String home(@RequestParam(name = "id",defaultValue = "1")int id,
                       @RequestParam(name = "goodsName",required = false) String goodsName,
                       @RequestParam(name="bbsId",required = false) Integer bbsId,
                       Model model, HttpSession session){

        model.addAttribute("selectTag",id);
        model.addAttribute("goodsName","");
        model.addAttribute("userName",session.getAttribute("userName"));
        model.addAttribute("typeList",vTypeRepository.findAllGroupBySuperId());
        model.addAttribute("top3Goods",
                vGoodsRepository.findTop3BySoldTotalGreaterThanEqualOrderBySoldTotalDesc(1));
        model.addAttribute("topPicture",pictureRepository.findTop1ByOrderByGoodsIdDesc());
        model.addAttribute("top5BBS",bbsRepository.findTop5ByOrderByUpdateTimeDesc());
        model.addAttribute("vTypeRepository", vTypeRepository);
        switch (id){
            case 1:
                // 商品排序 需要
                model.addAttribute("goodsTop4New",goodsRepository.findTop4ByIsNewEqualsOrderByGoodsCreatedTimeDesc(1));
                model.addAttribute("goodsTop4Heat",goodsRepository.findTop4ByGoodsHitGreaterThanOrderByGoodsCreatedTimeDesc(1));
                model.addAttribute("goodsTop4Sale",goodsRepository.findTop4ByIsSaleEqualsOrderByGoodsCreatedTimeDesc(1));
                break;
            case 2:
                model.addAttribute("allGoods",vGoodsRepository.findAll());
                break;
            case 3:
                model.addAttribute("newGoods",vGoodsRepository.findAllByIsNewEquals(1));
                break;
            case 4:
                model.addAttribute("saleGoods",vGoodsRepository.findAllByIsSaleEquals(1));
                break;
            case 7:
                if(!StringUtils.isEmpty(goodsName) ){
                    model.addAttribute("allComments",commentRepository.findAllByGoodsNameLike("%"+goodsName+"%"));
                }else
                    model.addAttribute("allComments",commentRepository.findAll());
                break;
            case 8:
                Optional<BBS> byId = bbsRepository.findById(bbsId);
                byId.ifPresent(bbs -> model.addAttribute("bbs", bbs));

                break;
        }

        return "/index";
    }



//    @RequestMapping(value = "/",method = RequestMethod.POST)
//    public String homeSearchByType(@RequestParam(name = "id",defaultValue = "1")int id,
//                                   @RequestParam(name = "key") String key,
//                             @RequestParam(name = "type",defaultValue = "0" ) int type,
//                             Model model, HttpSession session){
//
//        model.addAttribute("selectTag",id);
//        model.addAttribute("goodsName","aaaa");
//        model.addAttribute("userName",session.getAttribute("MemberName"));
//        model.addAttribute("typeList",vTypeRepository.findAllGroupBySuperId());
//        model.addAttribute("top3Goods",
//                vGoodsRepository.findTop3BySoldTotalGreaterThanEqualOrderBySoldTotalDesc(1));
//        model.addAttribute("topPicture",pictureRepository.findTop1ByOrderByGoodsIdDesc());
//        model.addAttribute("top5BBS",bbsRepository.findTop5ByOrderByUpdateTimeDesc());
//        model.addAttribute("vTypeRepository", vTypeRepository);
//        switch (id){
//            case 6:
//                if(type == 0)
//                    model.addAttribute("searchGoods",vGoodsRepository.findAllByGoodsNameLike("%"+key+"%"));
//                else {
//
//                    List<SubType> allSubType = subTypeRepository.findAllBySuperTypeEquals(type);
//                    List<Integer> subTypes = Collections.emptyList();
//                    if(allSubType != null && !allSubType.isEmpty())
//                        for (SubType subType : allSubType) {
//                            subTypes.add(subType.getID());
//                        }
//
//                    model.addAttribute("searchGoods",vGoodsRepository.findAllByGoodsNameLikeAndSubIdIn(
//                            "%"+key+"%",subTypes));
//                }
//                break;
//        }
//
//        return "index";
//    }



    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String homeSearch(@RequestParam(name = "id",defaultValue = "1")int id,
                             @RequestParam(name = "cx",defaultValue = "") String cx,
                             @RequestParam(name = "key",defaultValue = "") String key,
                             @RequestParam(name = "type",defaultValue = "0" ) int type,

                             Model model, HttpSession session){

        model.addAttribute("selectTag",id);
        model.addAttribute("goodsName","aaaa");
        model.addAttribute("userName",session.getAttribute("userName"));
        model.addAttribute("typeList",vTypeRepository.findAllGroupBySuperId());
        model.addAttribute("top3Goods",
                vGoodsRepository.findTop3BySoldTotalGreaterThanEqualOrderBySoldTotalDesc(1));
        model.addAttribute("topPicture",pictureRepository.findTop1ByOrderByGoodsIdDesc());
        model.addAttribute("top5BBS",bbsRepository.findTop5ByOrderByUpdateTimeDesc());
        model.addAttribute("vTypeRepository", vTypeRepository);
        switch (id){
            case 5:

                model.addAttribute("searchGoods",vGoodsRepository.findAllByGoodsNameLike("%"+cx+"%"));
                break;

            case 6:
                if(type == 0)
                    model.addAttribute("searchGoods",vGoodsRepository.findAllByGoodsNameLike("%"+key+"%"));
                else {

                    List<SubType> allSubType = subTypeRepository.findAllBySuperTypeEquals(type);
                    List<Integer> subTypes = new ArrayList<>();
                    if(allSubType != null && !allSubType.isEmpty())
                        for (SubType subType : allSubType) {
                            subTypes.add(subType.getID());
                        }

                    model.addAttribute("searchGoods",vGoodsRepository.findAllByGoodsNameLikeAndSubIdIn(
                            "%"+key+"%",subTypes));
                }
                break;

        }

        return "/index";
    }


    @RequestMapping("/contact")
    public String contact(){
        return "/contact";
    }


    /**
     * 进入注册用户界面
     * @return
     */
    @GetMapping("/register")
    public String toRegister(){
        return "/register";
    }

    /**
     * 进入登录用户界面
     */
    @GetMapping("/login_user")
    public String toLogin(){
        return "/login_user";
    }

    /**
     * 检测登录用户信息
     */
    @PostMapping("/login_user_check")
    public String checkMember(@RequestParam("memberName") String userName,
                              @RequestParam("memberPWD") String pwd,
                              HttpSession session,
                              Model model){
        Optional<Member> memberNameEquals = memberRepository.findByMemberNameEquals(userName);
        if(memberNameEquals.isPresent()){
            Member member = memberNameEquals.get();
            if(!StringUtils.isEmpty(pwd)) {
                if (member.getMemberPWD().equals(pwd)) {
                    session.setAttribute("loginUser",userName);
                    model.addAttribute("userName",userName);
                    return "/index";
                }else {
                    model.addAttribute("msg","密码不正确");
                    return "/login_user";
                }
            }else {
                model.addAttribute("msg","密码为空");
                return "/login_user";
            }
        }else {
            model.addAttribute("msg","用户名不正确");
            return "/login_user";
        }
    }


    /**
     * 添加用户
     */
    @PostMapping("/register_deal")
    public String addMember(Member member){

        memberRepository.save(member);
        return "/login_user";
    }


    /**
     * 注销用户
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "/index";
    }





}
